package com.llp.javaweb.servlet;

import com.alibaba.fastjson.JSON;
import com.llp.javaweb.pojo.User;
import com.llp.javaweb.service.UserService;
import com.llp.javaweb.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;

@Slf4j
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置编码格式
        request.setCharacterEncoding("utf-8");
        //获取系统生成的验证码checkcodeserv
        HttpSession session = request.getSession();
        String checkcodeserv = (String) session.getAttribute("checkcodeserv");

        BufferedReader reader = request.getReader();
        //获取json字符串，将其转为user对象
        String s = reader.readLine();
        User user = JSON.parseObject(s, User.class);
        //获取user.username用于查询是否已存在相同用户名
        String username = user.getUsername();
        //判断用户名是否存在
        User u = userService.selectByName(username);

        //获取用户输入的验证码
        String checkcode = user.getCheckcode();
        System.out.println("系统验证码"+checkcodeserv);
        System.out.println("用户验证码"+checkcode);

        //存在则返回userexist
        if (u != null) {
            response.getWriter().write("userexist");
        } else if (!checkcodeserv.equalsIgnoreCase(checkcode)) {
            response.getWriter().write("codeerr");
        } else {
            //添加用户，并返回成功
            userService.add(user);
            response.getWriter().write("success");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
